package com.hx.thread.condition;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Minghua Chen
 * @date 2020-09-06 09:55
 */
public class ConditionDemo {
    private static final Logger logger = LoggerFactory.getLogger(ConditionDemo.class);
    private ReentrantLock reentrantLock = new ReentrantLock();
    private Condition condition = reentrantLock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        ConditionDemo demo = new ConditionDemo();
        new Thread(() -> {
            try {
                demo.method2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        //
        demo.method1();
    }

    void method1() throws InterruptedException {
        reentrantLock.lock();
        System.out.println("获取锁成功"+Thread.currentThread().getName());
        try {
            logger.info("条件不满足,进入等待.");
            condition.await();
            logger.info("条件已满足,业务逻辑执行.");
        } finally {
            boolean locked = reentrantLock.isLocked();
            int holdCount = reentrantLock.getHoldCount();
            System.out.println("holdCount:"+holdCount);
            System.out.println("是否还持有锁"+locked);
            reentrantLock.unlock();
            System.out.println("释放锁"+Thread.currentThread().getName());
        }
    }

    void method2() throws InterruptedException {
        reentrantLock.lock();
        System.out.println("获取锁成功"+Thread.currentThread().getName());
        try {
            logger.info("5s的执行时间");
            Thread.sleep(5000);
            logger.info("执行完毕,唤醒其他线程");
            condition.signal();
        } finally {
            int holdCount = reentrantLock.getHoldCount();
            System.out.println("holdCount:"+holdCount);
            reentrantLock.unlock();
            System.out.println("释放锁"+Thread.currentThread().getName());
            boolean locked = reentrantLock.isLocked();
            System.out.println("是否还持有锁"+locked);
        }
    }
}
